package com.ray.common.util;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * @author 张代浩
 * @date 2013-08-11 09:47:30
 * @version V1.0
 */
public class CommUtils {
	private static final SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.DATETIME_FORMAT);
	/**
	 * 排除相应名称的属性，返回剩余属性键对 String filterName[]={"name1","name2","name3"};
	 * 
	 * @param filterName
	 * @return
	 */
	public static Map attributeMapFilter(Map map, String[] filterName) {
		for (int i = 0; i < filterName.length; i++) {
			if (map.containsKey(filterName[i]))
				map.remove(filterName[i]);
		}
		return map;
	}

	public static String attributeStringFilter(String[] str, String[] filterName) {
		List<String> list = new ArrayList<String>();
		for (String s : str) {
			boolean tag = true;
			for (String f : filterName) {
				if (s.equals(f)) {
					tag = false;
					break;
				}
			}
			if (!tag) {
				list.add(s);
			}
		}

		return list.toString().replace(" ", "").replace("[", "").replace("]", "");
	}

	public static Map<String, Object> mapConvert(Map map) {
		Map<String, Object> dataMap = new HashMap<String, Object>(0);
		if (map != null) {
			Iterator it = map.entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry entry = (Map.Entry) it.next();
				Object ok = entry.getKey();
				Object ov = entry.getValue() == null ? "" : entry.getValue();
				String key = ok.toString();
				String[] value = new String[1];
				if (key.contains("date") || key.contains("time")) {
					value[0] = convertDateTime(key, ov);
				} else {
					if (ov instanceof String[]) {
						value = (String[]) ov;
					} else {
						value[0] = ov.toString();
					}
				}
				String keyval = value[0];
				for (int k = 1; k < value.length; k++) {
					keyval += "," + value[k];
				}
				dataMap.put(key, keyval);
			}
		}
		return dataMap;
	}

	private static String convertDateTime(String key, Object val) {
		if (StringUtils.isBlank(val.toString()))
			return "";

		String dt = "";
		if (val instanceof String[]) {
			dt = ((String[]) val)[0];
		} else {
			dt = val.toString();
		}

		try {
			dt = sdf.format(Date.parse(dt));
		} catch (Exception e) {
		}

		return dt;
	}

	public static Map<String, List<Map<String, Object>>> mapConvertMore(Map map, String tableName) {
		Map<String, List<Map<String, Object>>> fanalMap = new HashMap<String, List<Map<String, Object>>>();
		Map<String, Map<String, Object>> dataMap = new HashMap<String, Map<String, Object>>(0);
		Map<String, Object> mapField = null;
		if (map != null) {
			Iterator<?> it = map.entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry<String,Object> entry = (Map.Entry) it.next();
				Object ok = entry.getKey();
				Object ov = entry.getValue() == null ? "" : entry.getValue();
				String key = ok.toString();
				String keyval = "";
				String[] value = new String[1];
				if (ov instanceof String[]) {
					value = (String[]) ov;
				} else {
					value[0] = ov.toString();
				}
				keyval += value[0];
				for (int k = 1; k < value.length; k++) {
					keyval += "," + value[k];
				}
				String keyArr[] = key.split("\\.");
				mapField = new HashMap<String, Object>(0);
				if (keyArr.length == 1) {
					if (dataMap.get(tableName) != null) {
						mapField = dataMap.get(tableName);
					}
					mapField.put(keyArr[0], keyval);
					dataMap.put(tableName, mapField);
				} else if (keyArr.length == 2) {
					if (dataMap.get(keyArr[0]) != null) {
						mapField = dataMap.get(keyArr[0]);
					}
					mapField.put(keyArr[1], keyval);
					dataMap.put(keyArr[0], mapField);
				}
			}
		}
		List<Map<String, Object>> listField = null;
		if (dataMap.size() > 0) {
			Iterator<?> it = dataMap.entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry<String,Object>  entry = (Map.Entry) it.next();
				String ok = entry.getKey();
				Map<String, Object> ov = (Map<String, Object>) entry.getValue();
				listField = new ArrayList<Map<String, Object>>();
				if (ok.indexOf("[") != -1) {
					ok = ok.substring(0, ok.indexOf("["));
				}
				if (fanalMap.get(ok) != null) {
					listField = fanalMap.get(ok);
				}
				listField.add(ov);
				fanalMap.put(ok, listField);

			}
		}
		return fanalMap;
	}


	/**
	 * 去除字符串中的空格、回车、换行符、制表符
	 * 
	 * @param str
	 * @return \n 回车(\u000a) \t 水平制表符(\u0009) \s 空格(\u0008) \r 换行(\u000d)
	 */
	public static String replaceBlank(String str) {
		String dest = "";
		if (str != null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}

	/**
	 * 去除字符串中的空格、回车、换行符、制表符
	 * 
	 * @param str
	 * @return \n 回车(\u000a) \r 换行(\u000d)
	 */
	public static String replaceEnter(String str) {
		String dest = "";
		if (str != null) {
			Pattern p = Pattern.compile("\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}

	/**
	 * 根据字符串，回复数组
	 * 
	 * @param str
	 * @return Long
	 */
	public static Long[] getdicId(String ids) {
		Long[] result = null;
		if (ids != null && (!"".equals(ids))) {
			String[] ids_arr = ids.split(",");
			result = new Long[ids_arr.length];
			for (int i = 0; i < ids_arr.length; i++) {
				if (ids_arr[i] != null && (!"".equals(ids_arr[i]))) {
					result[i] = Long.valueOf(ids_arr[i]);
				}
			}
		}
		return result;
	}
	/**
	 * list转换成逗号分隔
	 * @param lst
	 * @param name
	 * @return
	 */
	public static String getListToString(List<?> lst,String name){
		String msg ="";
		 if(lst==null||lst.size()==0)
			 return null;
		 if(name==null||"".equals(name))
			 return null;
		 
		 Iterator<?> it = lst.iterator();
		  while (it.hasNext()){
			 Object ob=  it.next();
			  try {
			 msg +=","+BeanUtils.getSimpleProperty(ob, name);
			} catch (Exception e) {
 				e.printStackTrace();
				return  null;
			}  
		  }
		 return (msg==null||"".equals(msg))? null:msg.substring(1);
		 
	}
	
	/**
	 * json转换成逗号分隔
	 * @param lst
	 * @param name
	 * @return
	 */
	public static String getJsonToString(String lst, String name) {
		String msg = "";
		if (lst == null || "".equals(lst)||"null".equals(lst))
			return null;
		if (name == null || "".equals(name))
			return null;
		try {
			JSONArray jsonarr = JSON.parseArray(lst);
			boolean mulShow = false;//是否杂合显示中英文 例如：刘德华(andy)
			if (name.indexOf("|")>0) {
				mulShow = true;
			}
			for (Object ob : jsonarr) {
				JSONObject jsonobj = (JSONObject) ob;
				if (mulShow) {
					msg += "," + jsonobj.getString(name.split("\\|")[0])+"("+jsonobj.getString(name.split("\\|")[1])+")";
				}else{
					msg += "," + jsonobj.getString(name);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		return (msg == null || "".equals(msg)) ? null : msg.substring(1);

	}
	
	/**
	 * 根据01转为NY
	 * @param id
	 * @param gcrDictionaryService
	 * @return 
	 */
	public  static String getNumToCode(String Num, String str) {
		if(str.equals("NumToCode") && StringUtils.isNotBlank(Num)){
			if("0".equals(Num)){
				return "N";
			}else if("1".equals(Num)){
				return "Y";
			}
			return Num;
		}
		return null;
	}
	/**
	 * 根据01转换NY
	 * @param Num
	 * @return
	 */
	public static String getNumToCode(String Num){	
		return getNumToCode(Num, "NumToCode");
	}
	/**
	 * 根据01转换NY
	 * @param Num
	 * @return
	 */
	public static String getNumToCode(Long Num){	
		return getNumToCode(Num+"", "NumToCode");
	}
	/**
	 * 判断数组内重复元素
	 * @param msgarr
	 * @return
	 */
	public static String getduplicate(String[] msgarr) {

		if (msgarr == null)
			return null;
		else if (msgarr.length > 1) {
//			String[] duplicatearr = new String[msgarr.length];
			String msg ="",comma="";
			Set<String> arrset = new HashSet<String>();
			for (int i = 0; i < msgarr.length; i++) {
				if (arrset.contains(msgarr[i])) {
//					duplicatearr[i] = msgarr[i];
					msg+=comma+msgarr[i];
					comma=",";
				} else {
					arrset.add(msgarr[i]);
				}
			}
			return !"".equals(msg) ? msg : null;
		} else
			return null;
	}
	/**
	 * 数组转字符
	 * @param strarr
	 * @return
	 */
	public static String stringArrToString(String[] strarr,String separator){
		if(strarr==null||strarr.length<1)
			return "";
		String  msg ="",comma="";
		for(String str :strarr){
			if(str!=null&&!"".equals(str)){
				msg +=comma+str;
				comma=separator;
			}
		}
		return  msg;
		
	}
	public static String stringArrToString(String[] strarr){
		return stringArrToString(strarr,",");
	}

  }
